"""调拨单改造"""

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression

class SaleOrder(models.Model):
    _inherit = 'sale.order'

    @api.multi
    def action_confirm(self):
        """当产品控制策略是订购数量，则生成预发票明细"""
        res = super().action_confirm()
        for sale in self:
            order_policy_lines = sale.order_line.filtered(lambda x: x.product_id.invoice_policy == 'order')
            self.env['pre.account.line'].create_pre_account_line(sale_lines=order_policy_lines)
        return res

    @api.multi
    def nd_view_account_line(self):
        """查看以生成的发票明细"""
        self.ensure_one()
        lines_ids = self.order_line.mapped('pre_account_line_ids')
        if not lines_ids:
            raise UserError('还没有生成发票明细')
        tree_view = self.env.ref('nd_account.NDPreAccountLineViewTree')
        form_view = self.env.ref('nd_account.NDPreAccountLineViewFORM')
        return {
            'name': '发票明细',
            'type': 'ir.actions.act_window',
            'res_model': 'pre.account.line',
            'views': [(tree_view.id, 'tree'), (form_view.id, 'form')],
            'domain': [('id', 'in', lines_ids.ids)]
        }


class PurchaseOrder(models.Model):
    _inherit = 'purchase.order'
    get_product = fields.Selection([('all', '全部收货'), ('not all', '部分收货'), ('no', '未收货')], string='收货状态',
                                       compute='_get_product',store=True)

    invoice_status = fields.Selection([
        ('no', 'Nothing to Bill'),
        ('to invoice', 'Waiting Bills'),
        ('invoiced', 'No Bill to Receive'),
        ('not all','部分账单')
    ], string='Billing Status', compute='_get_invoiced', store=True, readonly=True, copy=False, default='no')
    @api.depends('order_line')
    def _get_product(self):
        for order in self:
            if order.state =='purchase':
                product_qyt = sum(order.order_line.mapped('product_qty'))
                qty_received = sum(order.order_line.mapped('qty_received'))
                if qty_received == 0:
                    order.get_product = 'no'
                elif product_qyt == qty_received:
                    order.get_product = 'all'
                else:
                    order.get_product = 'not all'

    @api.depends('state', 'order_line.qty_invoiced', 'order_line.qty_received', 'order_line.product_qty')
    def _get_invoiced(self):
        for order in self:
            if order.state not in ('purchase', 'done'):
                order.invoice_status = 'no'
                continue
            qty_invoiced = sum(order.order_line.mapped('qty_invoiced'))
            qty_received = sum(order.order_line.mapped('qty_received'))
            if qty_invoiced==0:
                order.invoice_status = 'to invoice'
            elif qty_invoiced==qty_received:
                order.invoice_status = 'invoiced'
            elif qty_received>qty_invoiced:
                order.invoice_status = 'not all'
            else:
                order.invoice_status = 'no'

    @api.multi
    def button_confirm(self):
        """当产品控制策略是订购数量，则生成预发票明细"""
        res = super().button_confirm()
        for purchase in self:
            purchase_policy_lines = purchase.order_line.filtered(lambda x: x.product_id.purchase_method == 'purchase')
            self.env['pre.account.line'].create_pre_account_line(purchase_lines=purchase_policy_lines)
        return res

    @api.multi
    def nd_view_account_line(self):
        """查看以生成的发票明细"""
        self.ensure_one()
        lines_ids = self.order_line.mapped('pre_account_line_ids')
        if not lines_ids:
            raise UserError('还没有生成发票明细')
        tree_view = self.env.ref('nd_account.NDPreAccountLineViewTree')
        form_view = self.env.ref('nd_account.NDPreAccountLineViewFORM')
        return {
            'name': '发票明细',
            'type': 'ir.actions.act_window',
            'res_model': 'pre.account.line',
            'views': [(tree_view.id, 'tree'), (form_view.id, 'form')],
            'domain': [('id', 'in', lines_ids.ids)]
        }


class StockPicking(models.Model):
    _inherit = 'stock.picking'

    nd_account_line_count = fields.Integer('发票明细数量', compute="_compute_nd_account_line_count", store=True)

    @api.depends('move_lines.pre_account_line_ids')
    def _compute_nd_account_line_count(self):
        for order in self:
            order.nd_account_line_count = len(order.move_lines.mapped('pre_account_line_ids'))

    @api.multi
    def action_done(self):
        """在调拨单验证的时候生成发票明细"""
        res = super().action_done()
        for pick in self:
            if pick.picking_type_code not in ['incoming', 'outgoing'] or pick.state != 'done':
                continue
            # proper_stock_moves = self.env['stock.move']
            # for move in pick.move_lines:
            #     if move.pre_account_line_ids or move.sale_line_id.pre_account_line_ids or move.purchase_line_id.pre_account_line_ids:
            #         continue
            #     proper_stock_moves |= move
            if not self.env.context.get('no_pre_account_line', False):
                self.env['pre.account.line'].create_pre_account_line(move_ids=pick.move_lines)
        return res

    # @api.multi
    # def nd_generate_account_line(self):
    #     """生成发票明细
    #     生成时机收到产品资料上的销售和采购的控制策略影响：
    #         1，如果是订购数量，就在销售、采购单确认时自动生成，
    #         2，如果是已交货/收获数量，就在调拨单确认时生成
    #         3，如果是退货，则一律在调拨单完成时生成"""
    #     self.ensure_one()
    #     not_invoiced_line = self.move_lines.filtered(lambda x: not x.pre_account_line_ids)
    #     pre_invoice_lines = self.env['pre.account.line'].create_pre_account_line(not_invoiced_line)

    @api.multi
    def nd_view_account_line(self):
        """查看以生成的发票明细"""
        self.ensure_one()
        lines_ids = self.move_lines.mapped('pre_account_line_ids')
        tree_view = self.env.ref('nd_account.NDPreAccountLineViewTree')
        form_view = self.env.ref('nd_account.NDPreAccountLineViewFORM')
        return {
            'name': '发票明细',
            'type': 'ir.actions.act_window',
            'res_model': 'pre.account.line',
            'views': [(tree_view.id, 'tree'), (form_view.id, 'form')],
            'domain': [('id', 'in', lines_ids.ids)]
        }


class SML(models.Model):
    _inherit = 'stock.move.line'

    @api.model
    def create(self, val):
        res = super().create(val)
        return res

    @api.multi
    def write(self, val):
        res = super().write(val)
        return res